<template>
	<div class="wareHous-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="订单号">
					<el-input v-model="state.queryParams.orderId" placeholder="订单号" clearable />
				</el-form-item>
				<el-form-item label="订单类型">
					<el-select v-model="state.queryParams.orderType" placeholder="请选择订单类型" clearable>
						<el-option v-for="(label, value) in orderTypeMap" :key="value" :label="label"
							:value="Number(value)" />
					</el-select>
				</el-form-item>
				<el-form-item label="订单状态">
					<el-select v-model="state.queryParams.orderStatus" placeholder="请选择订单状态" clearable>
						<el-option label="未开始" value="0" />
						<el-option label="进行中" value="1" />
						<el-option label="已完成" value="2" />
						<el-option label="暂停" value="3" />
						<el-option label="取消" value="4" />
						<el-option label="异常" value="5" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
					<el-button type="primary" icon="ele-Plus" @click="addWare">添加</el-button>
					<el-button type="primary" icon="ele-Download" @click="downloadTemplate">模版</el-button>
					<el-upload class="upload-demo" :before-upload="beforeUpload" :http-request="handleUpload"
						:show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError">
						<el-button icon="ele-Upload">导入</el-button>
					</el-upload>
					<el-button type="primary" icon="ele-Download" @click="exportDate">导出</el-button>
					<el-button type="danger" icon="ele-Warning" @click="batchDeleteOrder">批量删除</el-button>

				</el-form-item>

			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.OrderDate" style="width: 100%" v-loading="state.loading" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" prop="id" width="55" align="center" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="orderId" label="订单号" width="200" align="center" show-overflow-tooltip />
				<el-table-column prop="orderType" label="订单类型" width="200" align="center" show-overflow-tooltip>
					<template #default="scope">
						{{ orderTypeMap[scope.row.orderType as keyof typeof orderTypeMap] || '未知类型' }}
					</template>
				</el-table-column>

				<el-table-column prop="orderStatus" label="订单状态" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="primary" v-if="scope.row.orderStatus === 0">未开始</el-tag>
						<el-tag type="success" v-else-if="scope.row.orderStatus === 1">进行中</el-tag>
						<el-tag type="info" v-else-if="scope.row.orderStatus === 2">已完成</el-tag>
						<el-tag type="danger" v-else-if="scope.row.orderStatus === 3">暂停</el-tag>
						<el-tag type="warning" v-else-if="scope.row.orderStatus === 4">取消</el-tag>
						<!-- <el-tag type="warning" v-if="scope.row.orderStatus === 5">取消</el-tag> -->
						<el-tag type="default" v-else>未知类型</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="订单时间" width="200" align="center" show-overflow-tooltip />
				<!-- <el-table-column prop="trayCode" label="托盘条码" align="center" show-overflow-tooltip />
				<el-table-column prop="boxCode" label="箱条码" align="center" show-overflow-tooltip />
				<el-table-column prop="materialCode" label="物料编码" align="center" show-overflow-tooltip />
				<el-table-column prop="materialName" label="物料名称" align="center" show-overflow-tooltip />
				<el-table-column prop="batch" label="批次" align="center" show-overflow-tooltip />

				<el-table-column prop="number" label="数量" align="center" show-overflow-tooltip /> -->

				<!-- <el-table-column prop="reference" label="入-参考号" align="center" show-overflow-tooltip /> -->

				<el-table-column label-class-materialCode="not-allow-sortable" :resizable="false" />

				<el-table-column label="操作" width="250" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-InfoFilled" size="small" text @click="handleShoworderDetailInfo(scope.row)"
							v-auth="'sysTenant:update'"> 明细 </el-button>
						<el-button icon="ele-Check" size="small" text type="success"
							@click="executeHandle(scope.row)"> 执行 </el-button>
						<el-button icon="ele-Edit" size="small" text type="danger"
							@click="pauseOrderHandle(scope.row)"> 暂停 </el-button>
						<el-button icon="ele-Delete" size="small" text type="danger" @click="delWarehous(scope.row)"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditOrder ref="editEditOrderRef" :title="state.editTitle" @handleQuery="handleQuery" />


		<!-- 在其他弹窗后面添加条码明细弹窗 -->
		<!-- 条码明细弹窗 -->
		<el-dialog v-model="state.isShoworderDetailDialog" draggable :close-on-click-modal="false" width="900px"
			@closed="handleCloseorderDetailDialog">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
						<ele-InfoFilled /> </el-icon>
					<span>{{ $t('message.stock.sninfTitle') }}</span>
				</div>
			</template>
			<el-table :ref="orderDetailTableNameRef" :data="orderDetailTableData" style="width: 100%;height: 50vh;"
				@sort-change="orderDetailTableChangeSort" border>
				<!-- 序号 -->
				<el-table-column type="index" :label="$t('message.components.seq')" width="55" align="center" fixed />
				<!-- 数据字段 -->
				<template v-for="(item, index) in orderDetailTableHeader">
					<el-table-column v-if="item.isShow" :key="index" :prop="item.property" :label="item.label"
						class-materialCode="allow-sortable" :sortable="item.sortable === false ? false : 'custom'"
						:width="item.width ? item.width : ''">
						<template #header>
							<span>
								<el-tooltip class="item" effect="dark" :content="item.label" placement="top"
									:open-delay="1000">
									<span>{{ item.label }}</span>
								</el-tooltip>
							</span>
						</template>
						<template v-slot="scope">
							<!--            参数和钩子较多，且后续要优化，详情自己看组件-->
							<slTableText :type="item.type"
								:value="scope.row[item.property] === null ? '' : scope.row[item.property]"
								:index="scope.$index" />
						</template>
					</el-table-column>
				</template>

				<el-table-column label-class-materialCode="not-allow-sortable" :resizable="false" />
			</el-table>

			<el-pagination v-model:currentPage="orderDetailTableParams.page" v-model:page-size="orderDetailTableParams.pageSize"
				:total="orderDetailTableParams.total" :page-sizes="[1, 10, 20, 50, 100]" size="small" background
				@size-change="handleorderDetailInfoSizeChange" @current-change="handleorderDetailInfoIndexChange"
				layout="total, sizes, prev, pager, next, jumper" />

			<template #footer>

			</template>
		</el-dialog>

	</div>
</template>


<script lang="ts" setup name="order">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditOrder from './component/editOrderinfo.vue';
import slTableText from '/@/components/slTableText/index.vue'
import { getAPI } from '/@/utils/axios-utils';
import { downloadByData, getFileName } from '/@/utils/download';


import { OrderinfoApi, OrderinfoexportApi, DownloadOrderinfoApi, OrderinfoinportApi, BatchDeleteOrderInfoApi } from '/@/api-services/apis/warehouse-orderinfo-api';; // 导入 API 服务
import { getorderDetailDataAPI, executeOrderPost, pauseOrderPost } from '/@/api-wcs-services/order/orderinfo-api'; // 导入 API 服务
import { OrderInfo, DeleteOrderinfoInput } from '/@/api-services/models/order-input'; // 导入获取实体

import { error } from 'console';
import { nextTick } from 'process';


// ...其他导入

const editEditOrderRef = ref<InstanceType<typeof EditOrder>>();
const state = reactive({
	isShoworderDetailDialog : false,
	loading: false,
	OrderDate: [] as Array<OrderInfo>,
	queryParams: {
		orderId: undefined,
		orderStatus: undefined,
		materialCode: undefined,
		quality: undefined,
		orderType: undefined
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editTitle: '',
});

const orderTypeMap = {
	1: '暂存出库',
	2: '领料出库',
	3: '采货入库',
	4: '暂存入库',
	5: '其他入库（整托）',
	6: '其他入库（散托）',
	7: '回流入库'
};

onMounted(async () => {
	//console.log('当前路由参数:', route); // 添加路由参数调试
	// if (editEditOrderRef.value) {
	// 	editEditOrderRef.value.openDialog(null);
	// }
	console.log('当前路由参数:', editEditOrderRef.value); // 添加路由参数调试
	handleQuery();

});


// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {
		const res = await getAPI(OrderinfoApi).apiOrderinfoPagePost({
			...state.queryParams,
			page: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.OrderDate = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.OrderDate = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.orderId = undefined;
	state.queryParams.materialCode = undefined;
	state.queryParams.orderStatus = undefined;
	state.queryParams.orderType = undefined;
	state.queryParams.quality = undefined;
	handleQuery();
};

// 打开新增页面
const addWare = () => {
	const addData = {
		description: '',
		orderId: '',
		onMountedrderType: '',
		quality: '',
		orderStatus: '',
		materialCode: '',
		mboxCode: '',
		typeCode: '',
		number: 0,
		wave: '',
		batch: '',
		reference: '',
		outwarehosueDate: '',
		isdelete: 0,
	};
	state.editTitle = '出库订单';

	editEditOrderRef.value?.openDialog(addData);
};

// 假设存在一个方法可以获取选中行的数据，这里我们先定义一个 ref 来存储选中的行
const multipleSelection = ref<DeleteOrderinfoInput[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 获取选中行的 idlist
const selectedIds = computed(() => multipleSelection.value.map(item => ({ id: item.id })));
const deleteParams = { ids: selectedIds.value };

const batchDeleteOrder = async () => {
	if (selectedIds.value.length === 0) {
		ElMessage.warning('请选择要删除的1行');
		return;
	}
	console.log(selectedIds.value);
	try {
		await BatchDeleteOrderInfoApi(selectedIds.value);
		handleQuery(); // 刷新表格数据
		ElMessage.success('批量删除成功');
	} catch (error) {
		ElMessage.error('批量删除失败');
	}
};

// 关闭新增页面
const closeAddDialog = () => {
	editEditOrderRef.value?.openDialog(false);
};



// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editTitle = '编辑出库';
	editEditOrderRef.value?.openDialog(row);
};

// 删除操作
const delWarehous = (row: any) => {
	ElMessageBox.confirm(`确定删除订单：【${row.orderId}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await getAPI(OrderinfoApi).apiOrderinfoDeletePost({ id: row.id });
				handleQuery();
				ElMessage.success('删除成功');
			} catch (error) {
				// console.error('删除失败:', error);
				ElMessage.error('删除失败，请稍后重试');
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};

const exportDate = async () => {
	try {
		state.loading = true;
		// 通常导出文件时需要设置 responseType 为 'blob'，以正确处理二进制数据
		// 为了解决类型不匹配问题，将 responseType 单独传递
		const config = { responseType: 'blob' };
		var res = await OrderinfoexportApi(state.queryParams, 'blob');
		state.loading = false;
		var fileName = getFileName(res.headers);
		// 假设增加一些日志记录，方便调试
		console.log('准备开始下载文件，文件数据:', res.data, '文件名:', fileName);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
}
// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
	const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
		file.type === 'application/vnd.ms-excel'
	if (!isExcel) {
		ElMessage.error('只能上传 Excel 文件!')
		return false
	}
	return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
	const formData = new FormData()
	formData.append('file', options.file)
	// 这里调用你的上传API
	//console.log('handleUpload', formData);
	try {

		const response = await OrderinfoinportApi(formData).then((response) => {
			console.log('response', response);
			handleUploadSuccess(response);

		})

	} catch (error) {
		console.log('error', error);
		handleUploadError(error);
	}
}


// 上传成功回调
const handleUploadSuccess = async (response: any) => {
	console.log('response', response);
	if (response.status === 200) {
		ElMessage.success('导入成功')
		handleQuery() // 刷新表格数据
	}
	else {
		ElMessage.error(response.message || '导入失败')
	}
}

// 上传失败回调
const handleUploadError = (error: any) => {
	ElMessage.error(error.message || '导入失败' + error.message)
}

const downloadTemplate = async () => {
	try {
		DownloadOrderinfoApi().then((response) => {

			const blob = new Blob([response.data])
			const fileName = getFileName(response.headers);
			downloadByData(response.data as any, fileName);

			ElMessage.success(`下载成功${fileName}`);
		}); // 调用下载模板的API

	} catch (error) {
		ElMessage.error('下载失败');
	}
};


// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

// #endregion



// 执行订单
const executeHandle = (row: any) => {
	ElMessageBox.confirm(`确定执行订单：【${row.orderId}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await executeOrderPost({ id: row.id });
				handleQuery();
				ElMessage.success('执行成功');
			} catch (error) {
				// console.error('删除失败:', error);
				// ElMessage.error('执行失败，请稍后重试' + error);
			}
		})
		.catch(() => {
			ElMessage.info('已取消');
		});
};

// 执行订单
const pauseOrderHandle = (row: any) => {
	ElMessageBox.confirm(`确定暂停订单：【${row.orderId}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await pauseOrderPost({ id: row.id });
				handleQuery();
				ElMessage.success('暂停成功');
			} catch (error) {
				// console.error('删除失败:', error);
				// ElMessage.error('执行失败，请稍后重试' + error);
			}
		})
		.catch(() => {
			ElMessage.info('已取消');
		});
};


// #region 弹窗明细

// 添加条码明细表格数据
// refs
const orderDetailTableNameRef = ref()
const orderDetailTableData = ref([])
const orderDetailTableParams = reactive({
    page: 1,
		pageSize: 20,
		total: 0,
    field: '',
    order: ''
});

const orderDetailTableHeader = reactive([
	{
		label: "序号",
		property: 'serialNumber',
		type: undefined,
		isShow: true,
		sortable: true,
		width: 150
	},
	{
		label: '托盘',
		property: 'tray',
		type: undefined,
		sortable: true,
		isShow: true,
		width: 150
	},
	{
		label: '出库口',
		property: 'entranceandExit',
		type: undefined,
		isShow: true,
		sortable: true,
		width: 150
	},
	{
		label: '状态',
		property: 'status',
		type: 'orderDetailStatus',
		isShow: true,
		sortable: true,
		width: 150
	}
])

const orderDetailSearchList = reactive({
	pickingNumber: undefined,
	warehouseCode: undefined,
	warehouseName: undefined,
	locationId: undefined,
	locationCode: undefined,
	locationName: undefined,
	materialId: undefined,
	materialCode: undefined,
	materialName: undefined,
})

// 添加查看条码明细方法
const handleShoworderDetailInfo = async (row: any) => {
  try {
    state.loading = true

    orderDetailSearchList.pickingNumber = row.orderId


    handleorderDetailQuery()
    state.isShoworderDetailDialog = true
  } catch (error) {
    console.error(error)
  } finally {
    state.loading = false
  }
}

// 关闭条码明细弹窗
const handleCloseorderDetailDialog = () => {
  state.isShoworderDetailDialog = false
  orderDetailTableData.value = []
  orderDetailTableParams.total = 0
}


// 改变页面容量
const handleorderDetailInfoSizeChange = (val: number) => {
	orderDetailTableParams.pageSize = val;
	handleorderDetailQuery();
};

// 改变页码序号
const handleorderDetailInfoIndexChange = (val: number) => {
	orderDetailTableParams.page = val;
	handleorderDetailQuery();
};

// 表格排序
const orderDetailTableChangeSort = (column: any) => {
  if (!column.order) {
    orderDetailTableParams.field = ''
    orderDetailTableParams.order = ''
  }
  else {
    orderDetailTableParams.field = column.prop
    orderDetailTableParams.order = column.order
  }
  handleorderDetailQuery();
};

// 全局共用查询数据函数
const handleorderDetailQuery = async () => {
  try {
    
    state.loading = true
    const queryData = {
      // 分页查询基础参数
      page: orderDetailTableParams.page,
      pageSize: orderDetailTableParams.pageSize,
      orderField: orderDetailTableParams.field,
      order: orderDetailTableParams.order,

      // 查询字段
      pickingNumber: orderDetailSearchList.pickingNumber,
    }
    
    const res = await getorderDetailDataAPI(queryData)
    orderDetailTableData.value = res.data.result.items || []
    orderDetailTableParams.total = res.data.result.total || 0

    orderDetailTableDoLayout()
  } catch (err) {
    console.error(err)
  } finally {
    state.loading = false	
  }
}

// 执行tableDoLayout修复Element表格错位bug
const orderDetailTableDoLayout = () => {
  setTimeout(() => {
    nextTick(() => {
      orderDetailTableNameRef.value?.doLayout()
    })
  }, 0)
}
// #endregion


</script>
